package com.xbh.realtime.tio.websocket;

import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.websocket.common.WsSessionContext;
import org.tio.websocket.server.WsServerAioListener;

/**
 * @MyWSAioListener:
 * @author: ZBoHang
 * @time: 2021/8/11 11:15
 */
public class MyWSAioListener extends WsServerAioListener {
    public static final MyWSAioListener me = new MyWSAioListener();

    @Override
    public void onAfterConnected(ChannelContext channelContext, boolean isConnected, boolean isReconnect) throws Exception {
        super.onAfterConnected(channelContext, isConnected, isReconnect);
        System.out.println("MyWSAioListener ---->>>> 建链后触发本方法，注：建链不一定成功，需要关注参数isConnected");
    }

    @Override
    public void onAfterDecoded(ChannelContext channelContext, Packet packet, int packetSize) throws Exception {
        super.onAfterDecoded(channelContext, packet, packetSize);
        System.out.println("MyWSAioListener ---->>>> 解码成功后触发本方法");
    }

    @Override
    public void onAfterReceivedBytes(ChannelContext channelContext, int receivedBytes) throws Exception {
        super.onAfterReceivedBytes(channelContext, receivedBytes);
        System.out.println("MyWSAioListener ---->>>> 接收到TCP层传过来的数据后");
    }

    @Override
    public void onAfterSent(ChannelContext channelContext, Packet packet, boolean isSentSuccess) throws Exception {
        super.onAfterSent(channelContext, packet, isSentSuccess);
        System.out.println("MyWSAioListener ---->>>> 消息包发送之后触发本方法");
    }

    @Override
    public void onAfterHandled(ChannelContext channelContext, Packet packet, long cost) throws Exception {
        super.onAfterHandled(channelContext, packet,cost);
        System.out.println("MyWSAioListener ---->>>> 处理一个消息包后");
    }

    @Override
    public void onBeforeClose(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) throws Exception {
        MyWSMsgHandler.destroyConnection();
        WsSessionContext wsSessionContext = (WsSessionContext) channelContext.getAttribute();

        if (wsSessionContext.isHandshaked()) {
            String msg = channelContext.getClientNode().toString() + "离开了           还有【" + MyWSMsgHandler.getConnectionCount() + "】人在线";
            System.out.println(msg);
            super.onBeforeClose(channelContext, throwable, remark, isRemove);
        }
    }
}
